package ca.uwo.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

/**
 * Base class for other classes that need this menu
 * 
 * @author tracyg
 * 
 */
public class BaseMenuActivity extends Activity implements BaseMenuActivityInterface{
	
	private static final String TAG_NAME = "BaseMenuActivity";

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

//		Log.i(TAG_NAME, "Got menu option " + item.getItemId());
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_info_item: {
//			Log.i(TAG_NAME, "Got info menu option");

			// show url in browser
			Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.info_url)));
			startActivity(browser);
			return true;
		}
		case R.id.menu_help_item: {
//			Log.i(TAG_NAME, "Got help menu option");
			showWebPage(getString(R.string.help_url));
			return true;
		}
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void showWebPage(String url) {
		Intent openHelpPage = new Intent(BaseMenuActivity.this,
				ca.uwo.android.ViewWebPage.class);
		openHelpPage.putExtra("URL", url);
		startActivity(openHelpPage);
	}
	
	/**
	 * Show an alert with the given message
	 * 
	 * @param String
	 *            the message to show the user
	 * @param boolean exit the activity if true, else just dismiss action
	 */
	protected void showAlert(String message, final boolean exit) {
		// create empty alert dialog for error
		final AlertDialog alert = new AlertDialog.Builder(this)
				.setTitle("Error").setIcon(android.R.drawable.ic_dialog_alert)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// close the current activity and return to the previous
						// one if exit is true
						if (exit)
							finish();

					}
				}).create();

		// show populated alert dialog based on error encountered
		alert.setMessage(message);

		alert.show();
	}
	
	/**
	 * Handle a generic exception reading the RSS feed
	 * 
	 * @param e
	 */
	protected void handleError(String error) {
//		Log.e(TAG_NAME, error);
		showAlert(error, true);
	}
	
	
	/**
	 * Handle a generic exception reading the RSS feed
	 * 
	 * @param e
	 */
	protected void handleException(Exception e, String error) {

//		Log.e(TAG_NAME, error + ".  " + e.getMessage(), e);
		showAlert(error, true);
	}

	
}
